<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>文件上传与下载 - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-04-26 10:28">
      April 26, 2019 am
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.9k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      27
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="学习笔记-Java-web之文件的上传与下载"><a href="#学习笔记-Java-web之文件的上传与下载" class="headerlink" title="学习笔记 : Java web之文件的上传与下载"></a>学习笔记 : Java web之文件的上传与下载</h2><h3 id="文件上传"><a href="#文件上传" class="headerlink" title="文件上传"></a>文件上传</h3><h4 id="如何实现文件上传"><a href="#如何实现文件上传" class="headerlink" title="如何实现文件上传"></a>如何实现文件上传</h4><p><em><code>Apache</code>组织提供了一个开源组件<code>Commons-FileUpload</code>( 依赖于<code>common-io</code> ),该组件可以方便地将<code>multipart/form-data</code>类型请求中的各种表单解析出来,并实现一个或多个文件的上传,同时也可以限制上传文件的大小等内容..并且性能优异,使用简单. FileUpload组件是通过Servlet来实现文件上传功能的,其工作流程如下图所示.</em></p>
<p><img src="/2019/04/26/%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/FileUpload.png" srcset="/img/loading.gif" alt=" "></p>
<h4 id="文件上传相关API"><a href="#文件上传相关API" class="headerlink" title="文件上传相关API"></a>文件上传相关<code>API</code></h4><h5 id="FileItem-Interface"><a href="#FileItem-Interface" class="headerlink" title="FileItem Interface"></a>FileItem Interface</h5><p><em><code>FileItem</code>接口用于封装单个表单字段元素的数据,一个表单字段元素对应一个FileItem对象.</em></p>
<h5 id="DiskFileItemFactory-Class"><a href="#DiskFileItemFactory-Class" class="headerlink" title="DiskFileItemFactory Class"></a>DiskFileItemFactory Class</h5><p><em><code>DiskFileItemFactory</code>类用于将请求的消息实体中的每一个文件封装成单独的<code>FileItem</code>对象.如果上传的文件比较小,将直接保存在内存中,如果上传的文件比较大,则会以临时文件的形式,保存在磁盘的临时文件中,默认情况下,文件保存在内存/磁盘临时文件夹的临界值为10240,既10KB.</em></p>
<h5 id="ServletFileUpload-Class"><a href="#ServletFileUpload-Class" class="headerlink" title="ServletFileUpload Class"></a>ServletFileUpload Class</h5><p><em><code>ServletFileUpload</code>类是Apache组件处理文件上传的核心高级类,通过使用<code>parseRequest(HttpServletRequest)</code>方法可以将HTML中每个表单提交的数据封装成一个<code>FileItem</code>对象,然后以List列表的形式返回.</em></p>
<h4 id="文件上传案例"><a href="#文件上传案例" class="headerlink" title="文件上传案例"></a>文件上传案例</h4><ol>
<li><p><em>JSP页面代码</em></p>
<div class="hljs"><pre><code class="hljs html">&lt;%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
	&lt;head&gt;
		&lt;meta charset="UTF-8"&gt;
		&lt;title&gt;file&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;h3 align="center"&gt;upload the specified the file&lt;/h3&gt;
		&lt;hr&gt;
		&lt;form action="UploadServlet2" method="post"  enctype="multipart/form-data"&gt;
			&lt;div align="center"&gt;
				&lt;table&gt;
					&lt;tr&gt;
						&lt;td&gt;学号&lt;/td&gt;
						&lt;td&gt;&lt;input type="text" name="id"/&gt;
					&lt;/tr&gt;
					&lt;tr&gt;
						&lt;td&gt;姓名&lt;/td&gt;
						&lt;td&gt;&lt;input type="text" name="name"/&gt;&lt;/td&gt;
					&lt;/tr&gt;
					&lt;tr&gt;
						&lt;td&gt;照片&lt;/td&gt;
						&lt;td&gt;&lt;input type="file" name="image"/&gt;&lt;/td&gt;
					&lt;/tr&gt;
					&lt;tr&gt;
						&lt;td&gt;
							&lt;%-- 文件上传结果 --%&gt;
							&lt;%
								String result = (String)request.getAttribute("result");
								if(result!=null)&#123;
									out.println("&lt;script&gt;alert(' "+result+" ')&lt;/script&gt;");
								&#125;
							%&gt;
						&lt;/td&gt;
					&lt;/tr&gt;
				&lt;/table&gt;
				&lt;input type="submit" value="上传"/&gt;
			&lt;/div&gt;
		&lt;/form&gt;
	&lt;/body&gt;
&lt;/html&gt;</code></pre></div>
</li>
<li><p><em>Servlet类 : 获取表单及其上传文件的信息..</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.file.servlet;

<span class="hljs-keyword">import</span> java.io.File;
<span class="hljs-keyword">import</span> java.io.FileNotFoundException;
<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">import</span> javax.servlet.ServletException;
<span class="hljs-keyword">import</span> javax.servlet.annotation.WebServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletResponse;

<span class="hljs-keyword">import</span> org.apache.commons.fileupload.FileItem;
<span class="hljs-keyword">import</span> org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
<span class="hljs-keyword">import</span> org.apache.commons.fileupload.FileUploadException;
<span class="hljs-keyword">import</span> org.apache.commons.fileupload.disk.DiskFileItemFactory;
<span class="hljs-keyword">import</span> org.apache.commons.fileupload.servlet.ServletFileUpload;
<span class="hljs-keyword">import</span> org.apache.commons.io.filefilter.SuffixFileFilter;

<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/UploadServlet2"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UploadServlet2</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UploadServlet2</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		request.setCharacterEncoding(<span class="hljs-string">"utf-8"</span>);
		response.setCharacterEncoding(<span class="hljs-string">"utf-8"</span>);
		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);

		String message = <span class="hljs-string">"上传失败 !"</span>;<span class="hljs-comment">// 上传结果</span>

		<span class="hljs-comment">// FileItemFactory fileItemFactory = new DiskFileItemFactory();</span>
		DiskFileItemFactory fileItemFactory = <span class="hljs-keyword">new</span> DiskFileItemFactory();
		fileItemFactory.setSizeThreshold(<span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>);<span class="hljs-comment">// // 设置将上传的文件以临时文件的形式保存在磁盘的临界值</span>
		<span class="hljs-comment">// 默认情况下,采用的是系统默认的临时文件路径,可以通过该方式获取: System.getProperty("java.io.tmpdir");</span>
		fileItemFactory.setRepository(<span class="hljs-keyword">new</span> File(<span class="hljs-string">"D:\\Java web\\temporary files"</span>));<span class="hljs-comment">// 将上传的文件以临时文件的形式保存在指定的目录下</span>

		<span class="hljs-comment">// 判断请求消息中的内容是否是: multipart/form-data类型</span>
		<span class="hljs-keyword">if</span> (ServletFileUpload.isMultipartContent(request)) &#123;

			<span class="hljs-comment">// 文件上传的核心高级类</span>
			ServletFileUpload servletFileUpload = <span class="hljs-keyword">new</span> ServletFileUpload(fileItemFactory);
			servletFileUpload.setSizeMax(<span class="hljs-number">1024</span> * <span class="hljs-number">20</span>); <span class="hljs-comment">// 设置请求消息实体内容(既上传数据)的最大尺寸限制: 20KB</span>
			<span class="hljs-keyword">try</span> &#123;
				<span class="hljs-comment">// 将HTML中每个表单提交的数据封装成一个FileItem对象,然后以List列表的形式返回</span>
				List&lt;FileItem&gt; fileItems = servletFileUpload.parseRequest(request);

				<span class="hljs-comment">// 限制上传的文件类型</span>
				String[] suffixs = <span class="hljs-keyword">new</span> String[] &#123; <span class="hljs-string">".exe"</span>, <span class="hljs-string">".bat"</span>, <span class="hljs-string">".c"</span>, <span class="hljs-string">".java"</span>, <span class="hljs-string">".sh"</span>, <span class="hljs-string">"html"</span>, <span class="hljs-string">".css"</span>, <span class="hljs-string">".js"</span> &#125;;
				SuffixFileFilter suffixFileFilter = <span class="hljs-keyword">new</span> SuffixFileFilter(suffixs);

				<span class="hljs-comment">// 遍历集合</span>
				File file = <span class="hljs-keyword">null</span>;
				String sno = <span class="hljs-keyword">null</span>;
				String sname = <span class="hljs-keyword">null</span>;
				String fileName = <span class="hljs-keyword">null</span>;
				<span class="hljs-keyword">for</span> (FileItem fileItem : fileItems) &#123;
					String item = fileItem.getFieldName();
					<span class="hljs-keyword">if</span> (fileItem.isFormField()) &#123;<span class="hljs-comment">// 普通文本表单字段</span>
						<span class="hljs-keyword">if</span> (item.equals(<span class="hljs-string">"id"</span>)) &#123;
							sno = fileItem.getString();
						&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item.contentEquals(<span class="hljs-string">"name"</span>)) &#123;
							sname = fileItem.getString();
						&#125; <span class="hljs-keyword">else</span> &#123;
							System.out.println(<span class="hljs-string">"others value .."</span>);
						&#125;
					&#125; <span class="hljs-keyword">else</span> &#123;<span class="hljs-comment">// 文件表单字段</span>
						fileName = fileItem.getName();
						file = <span class="hljs-keyword">new</span> File(request.getSession().getServletContext().getRealPath(<span class="hljs-string">"/upload/"</span> + fileName));
						<span class="hljs-keyword">if</span> (suffixFileFilter.accept(file)) &#123;
							message = <span class="hljs-string">"禁止上传此类型文件 !"</span>;
						&#125; <span class="hljs-keyword">else</span> &#123;
							file.getParentFile().mkdirs();<span class="hljs-comment">// 创建目录</span>
							fileItem.write(file);<span class="hljs-comment">// 上传文件</span>
							message = <span class="hljs-string">"success to upload !"</span>;

							System.out.println(<span class="hljs-string">"id: "</span> + sno + <span class="hljs-string">"\nname: "</span> + sname + <span class="hljs-string">"\nthe file name: "</span> + fileName
									+ <span class="hljs-string">"\nthe file path: "</span> + file.getAbsolutePath()); <span class="hljs-comment">// 上传者及文件信息</span>
						&#125;
					&#125;
				&#125;

			&#125; <span class="hljs-keyword">catch</span> (FileNotFoundException e) &#123;
				message = <span class="hljs-string">"error : please choose the specified file !"</span>;
			&#125; <span class="hljs-keyword">catch</span> (SizeLimitExceededException e) &#123;
				message = <span class="hljs-string">"error : the file size exceeds limit !"</span>;
			&#125; <span class="hljs-keyword">catch</span> (FileUploadException e) &#123;
				e.printStackTrace();
			&#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;
				e.printStackTrace();
			&#125;
		&#125;
		<span class="hljs-comment">// 将提示信息保留在request对象中</span>
		request.setAttribute(<span class="hljs-string">"result"</span>, message);
		request.getRequestDispatcher(<span class="hljs-string">"upload.jsp"</span>).forward(request, response);
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果 : 略..</em></p>
</li>
</ol>
<h3 id="文件下载"><a href="#文件下载" class="headerlink" title="文件下载"></a>文件下载</h3><h4 id="文件下载程序流程"><a href="#文件下载程序流程" class="headerlink" title="文件下载程序流程"></a>文件下载程序流程</h4><p><em>浏览器通常会直接处理响应的实体内容,这时需要在<code>HTTP</code>响应消息中设置两个响应消息头字段,指定接收程序处理数据内容的方式为下载方式,当点击”下载”超链接时,系统将请求提交到对应的<code>Servlet</code>.在该Servlet中,程序流程如下 :</em></p>
<ol>
<li>根据该地址创建文件字节输入流.</li>
<li>通过该流读取下载文件的内容.</li>
<li>将读取的内容通过输出流写到目标文件中.</li>
</ol>
<ul>
<li><em><code>HTTP</code>中设置两个响应消息头,具体如下.</em><div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">//设定接收程序处理数据的方式</span>
Content-Disposition: attachment;filename=
<span class="hljs-comment">//设定实体内容的MIME类型</span>
Content-Type: application/x-msdownload</code></pre></div>


</li>
</ul>
<h4 id="文件下载案例"><a href="#文件下载案例" class="headerlink" title="文件下载案例"></a>文件下载案例</h4><ol>
<li><p><em>JSP页面代码</em></p>
<div class="hljs"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">%@</span> <span class="hljs-attr">page</span> <span class="hljs-attr">language</span>=<span class="hljs-string">"java"</span> <span class="hljs-attr">contentType</span>=<span class="hljs-string">"text/html; charset=UTF-8"</span>
    <span class="hljs-attr">pageEncoding</span>=<span class="hljs-string">"UTF-8"</span>%&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE html&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"Content-Type"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"text/html"</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>down the file<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
			<span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
			<span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"DownloadServlet?filename=文件.png"</span>&gt;</span>
				Click to download this file ..
			<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></code></pre></div>
</li>
<li><p><em>Servlet类 : 设置所要下载的文件以及文件在浏览器中打开的方式.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.file.servlet;

<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.io.InputStream;
<span class="hljs-keyword">import</span> java.io.OutputStream;
<span class="hljs-keyword">import</span> java.net.URLEncoder;

<span class="hljs-keyword">import</span> javax.servlet.ServletException;
<span class="hljs-keyword">import</span> javax.servlet.annotation.WebServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletResponse;

<span class="hljs-keyword">import</span> org.apache.tomcat.util.codec.binary.Base64;

<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/DownloadServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DownloadServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DownloadServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);

		<span class="hljs-comment">// 获取需要下载的文件名</span>
		String fileName = request.getParameter(<span class="hljs-string">"filename"</span>);
		<span class="hljs-comment">// 设定接收程序处理数据的方式( MIME type : application/octet-stream )</span>
		response.addHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/octet-stream"</span>);

		<span class="hljs-comment">/*
		 * 根据不同浏览器进行不同的编码处理,以防乱码
		 */</span>
		<span class="hljs-comment">// User-Agent: 首部包含了一个特征字符串,用来让网络协议的对端来识别发起请求的用户代理软件的应用类型、操作系统、软件开发商以及版本号.</span>
		String agent = request.getHeader(<span class="hljs-string">"User-Agent"</span>);
		<span class="hljs-keyword">if</span> (agent.toLowerCase().indexOf(<span class="hljs-string">"firefox"</span>) != -<span class="hljs-number">1</span>) &#123;
			response.addHeader(<span class="hljs-string">"Content-Disposition"</span>, <span class="hljs-string">"attachment;filename==?UTF-8?B?"</span>
					+ <span class="hljs-keyword">new</span> String(Base64.encodeBase64(fileName.getBytes(<span class="hljs-string">"UTF-8"</span>))) + <span class="hljs-string">"?="</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			<span class="hljs-comment">// 设定实体内容的MIME类型并使用encode(String s, Charset charset)解决乱码问题: Google Chrome,Microsoft Eage ..</span>
			response.addHeader(<span class="hljs-string">"Content-Disposition"</span>, <span class="hljs-string">"attachment;filename="</span> + URLEncoder.encode(fileName, <span class="hljs-string">"UTF-8"</span>));
		&#125;

		<span class="hljs-comment">// 读取文件</span>
		InputStream inputStream = getServletContext().getResourceAsStream(<span class="hljs-string">"/resource/"</span> + fileName);
		<span class="hljs-comment">// 获取response对象的输出流</span>
		OutputStream outputStream = response.getOutputStream();
		<span class="hljs-keyword">byte</span>[] buffer = <span class="hljs-keyword">new</span> <span class="hljs-keyword">byte</span>[<span class="hljs-number">1024</span>];
		<span class="hljs-keyword">int</span> len;
		<span class="hljs-keyword">while</span> ((len = inputStream.read(buffer)) != -<span class="hljs-number">1</span>) &#123;
			outputStream.write(buffer, <span class="hljs-number">0</span>, len);
		&#125;
		outputStream.close();
		inputStream.close();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果 : 略..</em></p>
</li>
</ol>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Java-web/">Java web</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/04/27/VOA-A-Lifetime-of-Exercise-Slows-Aging-Process/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">VOA:A Lifetime of Exercise Slows Aging Process</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/04/26/JSP-%E6%A0%87%E5%87%86%E6%A0%87%E7%AD%BE%E5%BA%93/">
                        <span class="hidden-mobile">JSP 标准标签库</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "文件上传与下载&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
